import math
import operator
import threading
import types
from functools import reduce

from PIL import Image, ImageFilter
import time
from PIL import ImageGrab
import pytesseract
import argparse
import cv2
import os
import pyautogui as pg
import json
from pynput.keyboard import Listener as keyListener
from pynput.mouse import Listener as  mouseListener
import pickle
config = {
    "key": "<105>",  # 监听的按键
    "screenRange": [133, 179, 1788, 1109]  # 截图的范围x1,y1,x2,y2
}
EVENT_TYPE_KEY = "KEY"
EVENT_TYPE_MOUSE = "MOUSE"

RELEASE_EVENT = False
PRESS_EVENT = True


class EventList():
    def __init__(self):
        self.eventList = []
        self.output = open("out.txt", "ba")

    def append(self, obj):
        self.eventList.append(obj)
        self.output.write(pickle.dumps(obj) )
        self.output.flush()

eventList = EventList()


def createEvent(eventType, eventKey, eventFlag, eventTime=time.time(), eventPos={}):
    event = myEvent()
    event.eventType = eventType
    event.eventKey = eventKey
    event.eventFlag = eventFlag
    event.eventTime = eventTime
    event.eventPos = eventPos
    print(event)
    return event


class myEvent():
    def __init__(self):
        self.eventType = ""
        self.eventKey = ""
        self.eventFlag = ""
        self.eventTime = ""
        self.eventPos = {}
    def toStr(self):
        return 't:{eventType},k:{eventKey},'
def on_pressKey(key):
    global eventList
    eventList.append({
        createEvent(
            eventType=EVENT_TYPE_KEY,
            eventKey=key,
            eventFlag=PRESS_EVENT
        )
    })


def on_releaseKey(key):
    global eventList
    eventList.append({
        createEvent(
            eventType=EVENT_TYPE_KEY,
            eventKey=key,
            eventFlag=RELEASE_EVENT
        )
    })


def on_pressMouse(x, y, key, flag):
    global eventList
    # print(a)
    # print(b)
    # print(c)
    # print(d)
    eventList.append({
        createEvent(
            eventType=EVENT_TYPE_MOUSE,
            eventKey=key,
            eventFlag=flag,
            eventPos={"x": x, "y": y}
        )
    })


# def on_releaseMouse(key):
#     global eventList
#     eventList.append({
#         createEvent(
#             eventType=EVENT_TYPE_MOUSE,
#             eventKey=key,
#             eventFlag=RELEASE_EVENT
#         )
#     })


if __name__ == '__main__':
    def mouseLis():
        with mouseListener(on_click=on_pressMouse) as listener:
            listener.join()


    def keyLis():
        with keyListener(on_press=on_pressKey, on_release=on_releaseKey) as listener:
            listener.join()


    threading.Thread(target=mouseLis).start()
    threading.Thread(target=keyLis).start()
